<?php
declare(strict_types=1);

namespace app\controller;

use app\traits\ResponseTrait;
use think\App;
use think\exception\ValidateException;
use think\Validate;
use Firebase\JWT\JWT;
use think\facade\Log;

/**
 * 控制器基础类
 */
abstract class BaseController
{
    use ResponseTrait;

    /**
     * Request实例
     * @var \think\Request
     */
    protected $request;

    /**
     * 应用实例
     * @var \think\App
     */
    protected $app;

    /**
     * 构造方法
     * @access public
     * @param  App  $app  应用对象
     */
    public function __construct(App $app)
    {
        $this->app     = $app;
        $this->request = $this->app->request;

        // 控制器初始化
        $this->initialize();
    }

    /**
     * 初始化
     */
    protected function initialize()
    {
        // 记录所有请求信息
        Log::info('Request Info', [
            'path' => request()->pathinfo(),
            'method' => request()->method(),
            'param' => request()->param()
        ]);
    }

    /**
     * 验证数据
     * @throws ValidateException
     */
    protected function validate(array $data, array $rules, array $message = []): array
    {
        $validate = new Validate();
        $validate->rule($rules);

        if (!empty($message)) {
            $validate->message($message);
        }

        if (!$validate->check($data)) {
            throw new ValidateException($validate->getError());
        }

        return $data;
    }

    /**
     * 生成JWT token
     */
    protected function createToken(int $userId, int $merchantId): string
    {
        $payload = [
            'iss' => 'wasass',
            'iat' => time(),
            'exp' => time() + env('JWT_EXPIRE', 7200),
            'user_id' => $userId,
            'merchant_id' => $merchantId
        ];
        
        return JWT::encode($payload, env('JWT_KEY'), 'HS256');
    }

    /**
     * 返回成功信息
     */
    protected function success($msg = 'success', $data = [])
    {
        return json([
            'code' => 0,
            'msg' => $msg,
            'data' => $data
        ]);
    }

    /**
     * 返回错误信息
     */
    protected function error($msg = 'error', $code = 1)
    {
        return json([
            'code' => $code,
            'msg' => $msg
        ]);
    }
} 